/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.organization.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.organization.domain.OfficeRecord;
import com.jeeplus.organization.domain.OfficeRequest;
import com.jeeplus.organization.service.OfficeRecordService;
import com.jeeplus.organization.service.OfficeRequestService;
import com.jeeplus.organization.service.dto.OfficeRecordDTO;
import com.jeeplus.organization.service.mapstruct.OfficeRecordWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 请示记录Controller
 * @author 淋漓
 * @version 2024-06-21
 */

@Api(tags ="请示记录")
@RestController
@RequestMapping(value = "/office/record")
public class OfficeRecordController {

	@Autowired
	private OfficeRecordService officeRecordService;

	@Autowired
	private OfficeRecordWrapper officeRecordWrapper;

	@Autowired
	private OfficeRequestService officeRequestService;

	/**
	 * 请示记录列表数据
	 */
	@ApiLog("查询请示记录列表数据")
	@ApiOperation(value = "查询请示记录列表数据")
	@PreAuthorize("hasAuthority('office:record:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<OfficeRecordDTO>> list(OfficeRecordDTO officeRecordDTO, Page<OfficeRecord> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (officeRecordDTO, OfficeRecordDTO.class);
		IPage<OfficeRecordDTO> result = officeRecordWrapper.toDTO ( officeRecordService.page (page, queryWrapper) );
		return ResponseEntity.ok (result);
	}

	/**
	 * 根据Id获取请示记录数据
	 */
	@ApiLog("根据Id获取请示记录数据")
	@ApiOperation(value = "根据Id获取请示记录数据")
	@PreAuthorize("hasAnyAuthority('office:record:view')")
	@GetMapping("queryById")
	public ResponseEntity<OfficeRecordDTO> queryById(String id) {
		return ResponseEntity.ok ( officeRecordWrapper.toDTO ( officeRecordService.getById ( id ) ) );
	}

	/**
	 * 保存请示记录
	 */
	@ApiLog("保存请示记录")
	@ApiOperation(value = "保存请示记录")
	@PreAuthorize("hasAnyAuthority('office:record:add','office:record:edit')")
	@PostMapping("save")
	public  ResponseEntity <String> save(@Valid @RequestBody OfficeRecordDTO officeRecordDTO) {
		if(officeRecordDTO.getId()!=null){
			officeRecordDTO.setDealTime(new Date());
			officeRecordService.saveOrUpdate (officeRecordWrapper.toEntity (officeRecordDTO));
			return ResponseEntity.ok ( "操作成功" );
		}
		OfficeRequest one = officeRequestService.getOne(new LambdaQueryWrapper<OfficeRequest>()
				.eq(OfficeRequest::getName, officeRecordDTO.getName()));
		officeRecordDTO.setId(one.getId());
		officeRecordDTO.setDeliverTime(new Date());
		//新增或编辑表单保存
		officeRecordService.saveOrUpdate (officeRecordWrapper.toEntity (officeRecordDTO));
        return ResponseEntity.ok ( "发送成功" );
	}


	/**
	 * 删除请示记录
	 */
	@ApiLog("删除请示记录")
	@ApiOperation(value = "删除请示记录")
	@PreAuthorize("hasAuthority('office:record:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        officeRecordService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除请示记录成功" );
	}

    /**
     * 导出请示记录数据
     *
     * @param officeRecordDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出请示记录数据")
    @PreAuthorize("hasAnyAuthority('office:record:export')")
    @GetMapping("export")
    public void exportFile(OfficeRecordDTO officeRecordDTO, Page <OfficeRecord> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (officeRecordDTO, OfficeRecordDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据

        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List < OfficeRecord> result = officeRecordService.page ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( officeRecordService, officeRecordWrapper ).exportExcel ( result,  options.getSheetName ( ), OfficeRecordDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入请示记录数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('organization:officeRecord:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( officeRecordService, officeRecordWrapper ).importExcel ( file, OfficeRecordDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入请示记录数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('organization:officeRecord:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "请示记录数据导入模板.xlsx";
        List<OfficeRecordDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( officeRecordService, officeRecordWrapper ).exportExcel ( list,  "请示记录数据", OfficeRecordDTO.class, fileName, null, response );
    }


}
